package com.yanyeori.framework.redis.util;

import com.yanyeori.framework.core.interfaces.PublishEventUtil;
import com.yanyeori.framework.core.util.IdUtil;
import com.yanyeori.framework.core.util.SpringUtil;
import com.yanyeori.framework.redis.constant.RedisConst;
import com.yanyeori.framework.redis.model.PushMessage;
import com.yanyeori.framework.redis.model.RemoteEvent;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * Redis发布事件工具
 *
 * @author chenkuan 2020/08/20
 */
public class RedisPublishEventUtil implements PublishEventUtil {

    private final RedisTemplate<String, Object> redisTemplate;

    public RedisPublishEventUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 发布事件
     *
     * @param event    事件
     * @param isRemote 是否远程(redis漫游事件/本地事件)
     */
    @Override
    public <T> void publishEvent(T event, boolean isRemote) {
        if (isRemote) {
            RemoteEvent<T> remoteEvent = new RemoteEvent<>();
            remoteEvent.setEventId(IdUtil.randomUUID());
            remoteEvent.setEvent(event);
            redisTemplate.convertAndSend(RedisConst.REDIS_EVENT_CHANNEL, new PushMessage(RedisConst.TOPIC_REDIS_EVENT_REMOTE_PUBLISH, remoteEvent));
        } else {
            SpringUtil.publishEvent(event);
        }
    }
}
